package com.visionet.waveletData.web.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import weibo4j.Account;
import weibo4j.Favorite;
import weibo4j.Oauth;
import weibo4j.Timeline;
import weibo4j.Users;
import weibo4j.Weibo;
import weibo4j.http.AccessToken;
import weibo4j.model.Favorites;
import weibo4j.model.Paging;
import weibo4j.model.Status;
import weibo4j.model.StatusWapper;
import weibo4j.model.User;
import weibo4j.model.WeiboException;

import com.google.common.collect.Lists;
import com.visionet.waveletData.web.common.utilities.MessageSourceHelper;
import com.visionet.waveletData.web.common.utilities.props.PropsUtil;

public class SinaUtil {
	
	public final static int SINA_PAGE_SIZE_TEN = 10;
	public final static int SINA_PAGE_SIZE_TWENTY = 20;
	private final static int SINA_PAGE_SIZE_FIFTY = 50;
	public final static int SINA_FIRST_PAGE_NUM = 1;

	// 第三方帐号显示内容
	// 关注
	public static final short FIRST_PAGE_TYPE_ATTENTION = 1;
	// 提到我的
	public static final short FIRST_PAGE_TYPE_ATME = 2;
	// 我的博文
	public static final short FIRST_PAGE_TYPE_MYSTATUS = 3;
	// 根据ID查询博文
	public static final short FIRST_PAGE_TYPE_GETBYID = 4;
	//我的收藏
	public static final short FIRST_PAGE_TYPE_COLLECTION = 5;
	
	//微博登陆用户密码统一为123456
	public static final String WEIBO_LOGIN_PASSWORD = "0OOOoOOoOo00";
	
	public static final String SINA_AUTHORIZE_URL = "https://api.weibo.com/oauth2/authorize?client_id=784909209&response_type=code&redirect_uri=http://192.168.16.10/weiboLogin";
//	public static final String SINA_AUTHORIZE_URL = "https://api.weibo.com/oauth2/authorize?client_id=784909209&response_type=code&redirect_uri=" + PropsUtil.getProperty("service.domain") + "weiboLogin";
	
	public static final String SINA_TITLE = MessageSourceHelper.GetMessages("app.common.utils.SinaUtil.news");
	
	private SinaUtil(){}

	public static String getSinaAuthorizeURL() throws Exception {
		String sinaAuthorizeUrl = PropsUtil.getProperty("service.domain") + "api/toSinaPage";
		return sinaAuthorizeUrl;
	}
	
	public static void setWeibo(String accessToken) {
		Weibo weibo = new Weibo();
		weibo.setToken(accessToken);
		// return weibo;
	}
	
	public static String getUid(String accessToken) throws Exception {
		Account am = new Account();
		am.client.setToken(accessToken);
		String uid = null;
		weibo4j.org.json.JSONObject json = am.getUid();
		uid = json.getString("uid");
		return uid;
	}
	
	public static User getUserInfo(String accessToken) throws Exception {
		String uid = getUid(accessToken);
		User user = null;
		if(uid != null){
			Users um = new Users();
			um.client.setToken(accessToken);
			user = um.showUserById(uid);
		}
		return user;
	}

	public static AccessToken getAccessToken(String code) throws Exception {
		AccessToken accessToken = null;
		if (code != null) {
			Oauth oauth = new Oauth();
			accessToken = oauth.getAccessTokenByCode(code);
		}
		return accessToken;
	}
	
	/**
	 * 根据分页数, 分页条数
	 * @param pageSize
	 * @param pageNum
	 * @param accessToken
	 * @return
	 * @throws Exception
	 */
	public static List<Status> getFriendTimelines(int pageSize, int pageNum, String sinceId, String accessToken) throws Exception {
		Paging p = wrapPaging(pageSize, pageNum, sinceId);
		return getStatusByType(FIRST_PAGE_TYPE_ATTENTION, p, accessToken);
	}
	
	private static Paging wrapPaging(int pageSize, int pageNum, String maxId){
		Paging p = new Paging(pageNum, pageSize);
		if(Validator.isNotNull(maxId)){
			p.setMaxId(Long.valueOf(maxId));
		}
		return p;
	}
	
	/**
	 * sinceId查询
	 * @param pageSize
	 * @param sinceId
	 * @param accessToken
	 * @return
	 * @throws Exception
	 */
	public static List<Status> getFriendTimelines(long sinceId, String accessToken) throws Exception {
		return getStatusByType(FIRST_PAGE_TYPE_ATTENTION, new Paging(1, SINA_PAGE_SIZE_FIFTY, sinceId), accessToken);
	}
	/**
	 * 根据分页数, 分页条数
	 * @param pageSize
	 * @param pageNum
	 * @param accessToken
	 * @return
	 * @throws Exception
	 */
	public static List<Status> getMentions(int pageSize, int pageNum, String sinceId, String accessToken) throws Exception {
		Paging p = wrapPaging(pageSize, pageNum, sinceId);
		return getStatusByType(FIRST_PAGE_TYPE_ATME, p, accessToken);
	}
	
	public static List<Status> getFavorite(int pageSize, int pageNum, String sinceId, String accessToken) throws Exception {
		Paging p = wrapPaging(pageSize, pageNum, sinceId);
		return getStatusByType(FIRST_PAGE_TYPE_COLLECTION, p, accessToken);
	}
	/**
	 * sinceId查询
	 * @param pageSize
	 * @param sinceId
	 * @param accessToken
	 * @return
	 * @throws Exception
	 */
	public static List<Status> getMentions(long sinceId, String accessToken) throws Exception {
		return getStatusByType(FIRST_PAGE_TYPE_ATME, new Paging(1, SINA_PAGE_SIZE_FIFTY, sinceId), accessToken);
	}
	/**
	 * 根据分页数, 分页条数
	 * @param pageSize
	 * @param pageNum
	 * @param accessToken
	 * @return
	 * @throws Exception
	 */
	public static List<Status> getUserTimelineByUid(String uid, int pageSize, int pageNum, String sinceId, String accessToken) throws Exception {
		Paging p = new Paging(pageNum, pageSize);
		if(Validator.isNotNull(sinceId)){
			p.setMaxId(Long.valueOf(sinceId));
		}
		return getStatusByType(FIRST_PAGE_TYPE_MYSTATUS, p, accessToken, uid);
	}
	/**
	 * sinceId查询
	 * @param pageSize
	 * @param sinceId
	 * @param accessToken
	 * @return
	 * @throws Exception
	 */
	public static List<Status> getUserTimelineByUid(String uid, long sinceId, String accessToken) throws Exception {
		return getStatusByType(FIRST_PAGE_TYPE_MYSTATUS, new Paging(1, SINA_PAGE_SIZE_FIFTY, sinceId), accessToken, uid);
	}
	
	public static List<Status> getStatusByType(int statusType, Paging page, String accessToken) throws Exception {
		return getStatusByType(statusType, page, accessToken, null);
	}
	
	public static List<Status> getStatusByType(int statusType, Paging page, String accessToken, String uid) throws Exception {
		List<Status> list = null;
//		setWeibo(accessToken);
		Timeline tm = new Timeline();
		tm.client.setToken(accessToken);
		if(statusType == FIRST_PAGE_TYPE_ATTENTION){
			list = tm.getFriendsTimeline(0, 0, page).getStatuses();
		}else if(statusType == FIRST_PAGE_TYPE_ATME){
			list = tm.getMentions(page, 0, 0, 0).getStatuses();
		}else if(statusType == FIRST_PAGE_TYPE_MYSTATUS){
			list = tm.getUserTimelineByUid(uid, page, 0, 0).getStatuses();
		}else if(statusType == FIRST_PAGE_TYPE_COLLECTION){
			Favorite f = new Favorite();
			f.client.setToken(accessToken);
			List<Favorites> flist = f.getFavorites(page);
			if(flist != null && flist.size() > 0){
				list = new ArrayList<Status>();
				for(Favorites fa: flist){
					list.add(fa.getStatus());
				}
			}
		}
		return list;
	}
	
	public static List<Status> getStatusByType(String sinceId, Short statusType, String accessToken, String uid) throws Exception {
		List<Status> status = null;
		if(statusType == FIRST_PAGE_TYPE_ATTENTION){
			//关注和我的博文
			if(Validator.isNotNull(sinceId)){
				//sinceId不为空,从给定id开始查询
				status = getFriendTimelines(Long.valueOf(sinceId), accessToken);
			}else{
				//sinecId为空,默认获取第一页的信息
				status = getFriendTimelines(SINA_PAGE_SIZE_FIFTY, SINA_FIRST_PAGE_NUM, null, accessToken);
			}
		}else if(statusType == FIRST_PAGE_TYPE_ATME){
			//@提到我的
			if(Validator.isNotNull(sinceId)){
				//sinceId不为空,从给定id开始查询
				status = getMentions(Long.valueOf(accessToken), accessToken);
			}else{
				//sinecId为空,默认获取第一页的信息
				status = getMentions(SINA_PAGE_SIZE_FIFTY, SINA_FIRST_PAGE_NUM, null, accessToken);
			}
		}else if(statusType == FIRST_PAGE_TYPE_MYSTATUS){
			//我的博文
			if(Validator.isNotNull(sinceId)){
				//sinceId不为空,从给定id开始查询
				status = getUserTimelineByUid(uid, Long.valueOf(sinceId), accessToken);
			}else{
				//sinecId为空,默认获取第一页的信息
				status = getUserTimelineByUid(uid, SINA_PAGE_SIZE_FIFTY, SINA_FIRST_PAGE_NUM, null, accessToken);
			}
		}
		return status;
	}
	
	
	
	public static String wrapImgTag(String imgUrl){
		return "<p><img src='"+imgUrl+"' style='max-width: 400px'/></p>";
	}
	
	public static void main(String[] args) throws Exception {
		String access_token = "2.00ypgS2C0xj5Hrf8492d47dewaduzB";
		System.out.println(getUserInfo(access_token));;
//		Timeline tm = new Timeline();
//		tm.client.setToken(access_token);
//		
//		try {
//			StatusWapper status = tm.getFriendsTimeline();
//			for(Status s : status.getStatuses()){
//				System.out.println(s.toString());
//			}
//			System.out.println(status.getNextCursor());
//			System.out.println(status.getPreviousCursor());
//			System.out.println(status.getTotalNumber());
//			System.out.println(status.getHasvisible());
//		} catch (WeiboException e) {
//			e.printStackTrace();
//		}
		
	}
	
	public static String replaceLinkToHtmlLink(String linkStr) {
		String newLinkHtml = linkStr;
		Pattern pattern = Pattern.compile("(http://|www){1,2}[^\u4e00-\u9fa5\\s]*?\\.(com|net|cn|me|tw|fr)[^\u4e00-\u9fa5\\s（）()]*");
//		Pattern pattern = Pattern.compile("(http://|ftp://|https://|www){0,1}[^\u4e00-\u9fa5\\s]*?\\.(com|net|cn|me|tw|fr)[^\u4e00-\u9fa5\\s]*");
		Matcher matcher = pattern.matcher(newLinkHtml);
		List<String> list = Lists.newArrayList();
		while (matcher.find()) {
			String htmlStr = matcher.group(0);
			if(list.contains(htmlStr)){
				continue;
			}
			list.add(htmlStr);
			String linkHtml = "<a href=\"" +htmlStr+"\" target=\"_blank\" >"+htmlStr+"</a>";
			newLinkHtml = newLinkHtml.replace(htmlStr, linkHtml);
			System.out.println(newLinkHtml);
		}
		return newLinkHtml;
	}
	
	
}
